package com.carcenter.store.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.carcenter.common.constant.redis.RedisConstant;
import com.carcenter.common.result.Result;
import com.carcenter.common.result.enums.impl.BusinessCode;
import com.carcenter.store.entity.AddressVo;
import com.carcenter.store.entity.StoreAddress;
import com.carcenter.store.service.StoreAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/store-address")
public class StoreAddressController {
    @Autowired
    private StoreAddressService storeAddressService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/getStoreAddressListByStoreId/{storeId}")
    public Result<?> getStoreAddressListByStoreId(@PathVariable Integer storeId){
        ValueOperations<String,List<AddressVo>> ops = redisTemplate.opsForValue();

        List<AddressVo> list = ops.get(RedisConstant.STORE_ADDRESS + ":" + storeId);
        List<AddressVo> addressVos = new ArrayList<>();
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        }else {
            addressVos=storeAddressService.updateAddressCashe(storeId);
        }
        return Result.ok(addressVos);
    }

    @PostMapping("/newAddress")
    public Result<StoreAddress> newAddress(@RequestBody StoreAddress storeAddress){

        StoreAddress storeAddress1 = storeAddressService.newAddress(storeAddress);
        return Result.ok(storeAddress1);
    }

    @PutMapping("/addAddressStoreId/{tempAddressId}/{storeId}")
    public Result<String> addAddressStoreId(@PathVariable Integer tempAddressId,@PathVariable Integer storeId){

        LambdaUpdateWrapper<StoreAddress> updateWrapper = Wrappers.lambdaUpdate(StoreAddress.class)
                .eq(StoreAddress::getId, tempAddressId)
                .set(StoreAddress::getStoreId, storeId);
        storeAddressService.update(updateWrapper);
        return Result.ok(BusinessCode.ADD_SUCCESS.getMessage());
    }


}
